import storage from 'store';
import expirePlugin from 'store/plugins/expire';
import { login, getInfo, logout } from '@/api/login';
import { ACCESS_TOKEN } from '@/store/mutation-types';
import { welcome } from '@/utils/util';

storage.addPlugin(expirePlugin);
const state = {
  token: '',
  name: '',
  welcome: '',
  avatar: '',
  roles: [],
  info: {}
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, { name, welcome }) => {
    state.name = name;
    state.welcome = welcome;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_INFO: (state, info) => {
    state.info = info;
  }
};

const actions = {
  // 登录
  Login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        console.log('userInfo', userInfo, response);
        const { data } = response;
        storage.set(ACCESS_TOKEN, data.token, new Date().getTime() + 7 * 24 * 60 * 60 * 1000);
        commit('SET_TOKEN', data.token);
        resolve();
      }).catch(error => {
        reject(error);
      });
    });
  },

  // 获取用户信息
  GetInfo({ commit }) {
    return new Promise((resolve, reject) => {
      // 请求后端获取用户信息 /api/user/info
      const token = storage.get(ACCESS_TOKEN);
      getInfo({ token }).then(response => {
        const { data } = response;

        if (!data) {
          reject(new Error('Verification failed, please Login again.'));
        }

        const { roles, name, avatar } = data;

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject(new Error('getInfo: roles must be a non-null array!'));
        }

        commit('SET_ROLES', roles);
        commit('SET_INFO', data);
        commit('SET_NAME', { name: name, welcome: welcome() });
        commit('SET_AVATAR', avatar);
        // 下游
        resolve(data);
      }).catch(error => {
        reject(error);
      });
    });
  },

  // 登出
  Logout({ commit, state }) {
    return new Promise((resolve) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '');
        commit('SET_ROLES', []);
        storage.remove(ACCESS_TOKEN);
        resolve();
      }).catch((err) => {
        console.log('logout fail:', err);
        // resolve()
      }).finally(() => {
      });
    });
  }

};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};